package com.atguigu.gulimail.product.service.impl;

import com.atguigu.gulimail.product.service.CategoryBrandRelationService;
import com.atguigu.gulimail.product.vo.Catalog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 树形结构
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> all = baseMapper.selectList(null);
        Map<Long, List<CategoryEntity>> collect = all.stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));
        /*List<CategoryEntity> result = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu,all));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());*/
        List<CategoryEntity> result = collect.get(0L).stream()
                .map((menu) -> {
                    menu.setChildren(getChildren(menu,collect));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return result;
    }

    /**
     * 删除节点
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查是否引用了这个菜单
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 获取分类的路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        this.findParentPath(catelogId, list);
        Collections.reverse(list);
        return list.toArray(new Long[list.size()]);
    }

    /**
     * 级联更新
     *
     * @param category
     */
    @Transactional
    @Override
    public void updateCascadeById(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getLevel1Categories() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> level1Categories = this.getLevel1Categories();
        Map<String, List<Catalog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查询一级分类下的二级分类
            List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(item2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
                    List<CategoryEntity> entities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item2.getCatId()));
                    if (entities !=null){
                        List<Catalog2Vo.Catalog3Vo> catelog3List = entities.stream().map(item3 -> {
                            Catalog2Vo.Catalog3Vo catelog3Vo = new Catalog2Vo.Catalog3Vo();
                            catelog3Vo.setCatalog2Id(item2.getCatId().toString());
                            catelog3Vo.setId(item3.getCatId().toString());
                            catelog3Vo.setName(item3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catelog3List);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return parent_cid;
    }

    private void findParentPath(Long catelogId,List<Long> path){
        path.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0){
            findParentPath(categoryEntity.getParentCid(), path);
        }
    }

    private List<CategoryEntity> getChildren(CategoryEntity menu, Map<Long, List<CategoryEntity>> collect) {
        if (collect.get(menu.getCatId())==null){
            return new ArrayList<>();
        }
        List<CategoryEntity> result = collect.get(menu.getCatId()).stream()
                .map(e -> {
                    e.setChildren(getChildren(e, collect));
                    return e;
                }).sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort())))
                .collect(Collectors.toList());
        return result;
    }
    private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> all) {
        List<CategoryEntity> result = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId()))
                .map(e -> {
                    menu.setChildren(getChildren(e, all));
                    return menu;
                }).sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort())))
                .collect(Collectors.toList());
        return result;
    }


}
